import { DataSource } from 'typeorm';
import { Role } from '../../../entities/role.entity';
import { Permission } from '../../../entities/permission.entity';

/**
 * 角色-权限关联表种子数据
 * 负责初始化角色和权限的关联关系
 */
export class RolePermissionSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行角色-权限关联种子
   */
  async run(): Promise<void> {
    console.log('开始初始化角色-权限关联数据...');

    const roleRepository = this.dataSource.getRepository(Role);
    const permissionRepository = this.dataSource.getRepository(Permission);

    // 查找管理员角色
    const adminRole = await roleRepository.findOne({
      where: { code: 'admin' },
      relations: ['permissions']
    });

    // 查找普通用户角色
    const userRole = await roleRepository.findOne({
      where: { code: 'user' },
      relations: ['permissions']
    });

    // 查找访客角色
    const guestRole = await roleRepository.findOne({
      where: { code: 'guest' },
      relations: ['permissions']
    });

    if (!adminRole || !userRole || !guestRole) {
      console.log('未找到基础角色，跳过角色-权限关联初始化');
      return;
    }

    // 查找所有权限
    const allPermissions = await permissionRepository.find();
    
    if (allPermissions.length === 0) {
      console.log('未找到权限，跳过角色-权限关联初始化');
      return;
    }

    // 为管理员分配所有权限
    adminRole.permissions = allPermissions;
    await roleRepository.save(adminRole);
    console.log(`为角色 ${adminRole.name} 分配了 ${allPermissions.length} 个权限`);

    // 为普通用户分配部分权限
    const userPermissions = allPermissions.filter(permission => 
      !permission.code.includes('manage') && 
      !permission.code.includes('admin')
    );
    userRole.permissions = userPermissions;
    await roleRepository.save(userRole);
    console.log(`为角色 ${userRole.name} 分配了 ${userPermissions.length} 个权限`);

    // 为访客分配只读权限
    const guestPermissions = allPermissions.filter(permission => 
      permission.code.includes('view') || 
      permission.code.includes('read')
    );
    guestRole.permissions = guestPermissions;
    await roleRepository.save(guestRole);
    console.log(`为角色 ${guestRole.name} 分配了 ${guestPermissions.length} 个权限`);

    console.log('角色-权限关联数据初始化完成');
  }
} 